<!DOCTYPE html>
<html>

<head>

    <meta charset="utf-8">
    <meta name="viewport"
          content="width=device-width,  user-scalable=no">

    <title>INSPINIA | Forgot password</title>
    <link rel="stylesheet" href="../../plugins/layui/css/layui.css"/>
    <link rel="stylesheet" href="../../css/fa.css"/>
    <link rel="stylesheet" href="../../css/icon.css"/>
    <link rel="stylesheet" href="../../css/ares_animate.min.css"/>
    <link rel="stylesheet" href="../../css/ares_hover_variant.min.css"/>
    <link rel="stylesheet" href="../../css/ares_reboot.css"/>
    <link rel="stylesheet" href="../../css/app.min.css"/>
    <link rel="stylesheet" href="../../css/iframe.css"/>

    <link href="../../legacy/plugins/bootstrap3.3.4/bootstrap.min.css" rel="stylesheet">
    <link href="../../legacy/css/bootstrap-overwrite.css" rel="stylesheet">
    <link href="../../legacy/plugins/jqpagination/jqpagination.css" rel="stylesheet">
    <link href="../../legacy/plugins/jqGrid/ui.jqgrid.css" rel="stylesheet">
    <link href="../../legacy/plugins/toastr/toastr.min.css" rel="stylesheet">
    <link href="../../legacy/plugins/iCheck/custom.css" rel="stylesheet">
    <!--<link href="../../legacy/css/style.css" rel="stylesheet">-->
    <link href="../../legacy/css/mandy-style.css" rel="stylesheet">
    <style>
        .div-message textarea {
            height: 100px;
            width: 100%;
        }

        /*     a{
                 text-decoration:underline;
                 color:#6d9dcd
             }*/

        .div-message table {
           /*  background-color: #FFFFFF; */
            width: 100%;
        }

        .div-message {
            width: 100%;
            /*margin-left: 15px;*/
            /*margin-right: -15px;*/
            display: inline-block;
            /*border:1px;*/
            border-left-color: #000000;
            vertical-align: top;
            margin-top: 0px;
            /*height: auto;*/

            overflow: visible;
        }

        hr {
            margin-top: 5px;
            margin-bottom: 5px;
        }

        .content-detail span {
            display: inline-block;
        }

        .border {
            border-bottom: 1px solid #e7eaec;
        }
        #select_is_read {
        	font-size: 14px; 
        	padding: 0;
        	height: 30px;
        	width: 80px;
        	margin-left: 10px;
        }
		.div-message .ibox-title {
			border-bottom: 1px #dddddd solid !important;
			height: 40px;
			line-height: 39px;
			border-top-left-radius: 10px;
			border-top-right-radius: 10px;
		}
		/* #div_message_list>div:nth-child(odd) {
			background-color: #F6F6F6;
		} */
		#div_message_list .feed-element {
			font-size: 14px;
		}
		#div_message_list .feed-element .well {
			background-color: #FFF2CB;
		}
		#div_message_list .feed-element tr {
			background: none;
		}
		.a-show-emr {
			padding: 5px 10px;
    		background-color: #42D0A7;
    		margin-left: 5px;
    		border-radius: 15px;
    		color:#fff;
		}
        .feed-element {
/*             background: rgba(255, 255, 255,.5); */
            background-color: white; 
            border-radius:10px;
            padding: 5px;
            margin-bottom: 10px;
            border-bottom:none;
        }
        #ibox-content {
        	padding: 10px;
        	background: rgba(226, 229, 238,.5);
        }


        #not-read-alarm {
            animation-duration: .2s;
        }
        @keyframes swing {
            20% {
                -webkit-transform: rotate(5deg);
                -ms-transform: rotate(5deg);
                transform: rotate(5deg);
            }
             40% {
				 -webkit-transform: rotate(-5deg);
				 -ms-transform: rotate(-5deg);
				 transform: rotate(-5deg);
			 }
			 60% {
				 -webkit-transform: rotate(5deg);
				 -ms-transform: rotate(5deg);
				 transform: rotate(5deg);
			 }
            80% {
                -webkit-transform: rotate(-5deg);
                -ms-transform: rotate(-5deg);
                transform: rotate(-5deg);
            }
            100% {
                -webkit-transform: rotate(0deg);
                -ms-transform: rotate(0deg);
                transform: rotate(0deg);
            }
        }
    </style>


</head>

<body>
<div class="div-message ibox" style='margin-bottom:0'>
    <div class="ibox-title" >
        <table>
            <tr>
                <td align="left" class="form-inline">
                    <label>消息类型</label>
                    <select onchange="loadNewData()" id="select_is_read"  class="form-control">
                        <option value="1">未读</option>
                        <option value="2">已读</option>
                        <option value="0">全部</option>
                    </select>
                </td>
            </tr>
        </table>
    </div>
    <div id="ibox-content" onclick="clickMessageDiv()">
        <div>
            <div class="feed-activity-list" id="div_message_list" style="overflow: auto;">
            </div>
        </div>
    </div>
</div>

<div id="div_message_new" class="hide">
    <div width="100%" class="message-table" style="margin-bottom: 5px;">

    </div>
</div>
</body>
<script src="../../plugins/jquery-3.2.1.min.js"></script>
<script src="../../legacy/plugins/jquery.cookie.js"></script>
<script src="../../legacy/plugins/jqGrid/i18n/grid.locale-en.js"></script>
<script src="../../legacy/plugins/jqGrid/jquery.jqGrid.min.js"></script>
<script src="../../legacy/plugins/jqpagination/jquery.jqpagination.min.js"></script>
<script src="../../legacy/plugins/toastr/toastr.min.js"></script>
<script src="../../legacy/plugins/iCheck/icheck.min.js"></script>
<script src="../../legacy/plugins/autosize.js"></script>
<script src="../../legacy/plugins/jquery.PrintArea.js"></script>
<script src="../../legacy/js/fast-recovery.js"></script>
<script src="../../legacy/js/reuse.js"></script>
<script type="text/javascript" src="../../plugins/layui/layui.js"></script>
<script type="text/javascript" src="../../aresExtends/config/layuiConfig.js"></script>
<script>
    var mandyServices;
    /**
     * 业务类型
     *
     * 1：发布转诊（接收者）
     * 2：发布转诊成功（发起者收到系统通知）
     * 3：转诊被接收
     * 4：转诊消息过期
     *
     * 5：发布了新的训练/评估-->治疗师（新任务）
     * 6：发布了新的训练 -->治疗师（新患者）
     * 7：发布了新的训练 -->治疗师长（新患者）
     * //8：发布了新的训练成功/评估 -->医生收到系统通知
     *
     * 9：治疗师长安排训练/评估排课给治疗师 -->治疗师（新任务）
     * //10：治疗师长安排训/评估练排课给治疗师成功 -->治疗师长收到系统通知
     *
     * 11：治疗师长取消治疗师的训练/评估排课 -->治疗师（任务被取消）
     * //12：治疗师长取消治疗师的训练/评估练排课成功 -->治疗师长收到系统通知
     *
     * 13：治疗师长将A训练/评估排课调整给B -->A治疗师（任务被取消）
     * 14：治疗师长将A训练/评估排课调整给B -->B治疗师（新增任务）
     * //15：治疗师长将A训练/评估排课调整给B成功 -->治疗师长收到系统通知
     *
     * 16：治疗师长将训练/评估患者P负责人A更换为B -->A治疗师（患者被重新安排）
     * 17：治疗师长将训练/评估患者P负责人A更换为B -->B治疗师（新增患者）
     * //18：治疗师长将训练/评估患者P负责人A更换为B成功 -->治疗师长收到系统通知
     *
     * 19：治疗师完成评估（不包含重新评估） -->医生收到评估结果
     * //20：治疗师完成评估（不包含重新评估） -->治疗师收到系统通知
     */
    var messageTitleArray = [
        "收到新的<span style='color:#429BCB;font-weight:bold'>转诊</span>消息，请及时关注", "您已成功发布了<span style='color:#429BCB;font-weight:bold'>转诊</span>信息", "您发布的转诊已有医院接诊，请及时关注。", "您发布的转诊消息已过期，请及时关注",
        "收到新的<span style='color:#24BD99;font-weight:bold'>任务</span>，请及时关注", "收到新的患者，请及时关注", "收到新的患者，请及时关注", "发布新的任务成功",
        "收到新的<span style='color:#24BD99;font-weight:bold'>任务</span>，请及时关注", "发布新的任务成功",
        "任务已被取消，请及时关注", "取消了一个任务",
        "任务已被取消，请及时关注", "收到新的<span style='color:#24BD99;font-weight:bold'>任务</span>，请及时关注", "重新安排任务成功",
        "患者被重新安排，请及时关注", "收到新的患者，请及时关注", "重新安排患者成功",
        "收到一个评估结果，请及时关注", "评估完成",
        "您已成功接诊，请及时关注"
    ];

    var currentPage = 1;
    var messagePageSize = 10;

    var searchTime = null;

    var divMessageList = $("#div_message_list");
    var referralTable = $("#div_referral .message-table");
    var mySendReferralTable = $("#div_my_send_referral .message-table");
    var receiveTable = $("#div_receive_referral .message-table");
    var evaluationTable = $("#div_evaluation .message-table");
    var referralTimeOutTable = $("#div_referral_time_out .message-table");
    var taskOrPatientTable = $("#div_message_new .message-table");

    var isClickMessageDiv = false;

    var unReadNum = $("#num-not-read");


    //让消息高跟屏幕适应
//    $(".div-message").height(document.body.offsetHeight-120);
//    $(".div-message").height($("#content_div").height()+150);

    //定时刷新数据
    //window.setInterval(intervalLoadNewData, 60000);
    function intervalLoadNewData() {
        //最后一次点击是消息栏的话就要等下次轮循才能触发
        if (!isClickMessageDiv) {
            loadNewData();
        }
        isClickMessageDiv = false;
    }

    function clickMessageDiv() {
        isClickMessageDiv = true;
    }


    function loadNextData() {

        var isRead = $("#select_is_read").val();

        if (searchTime != null) {
            $("#div_message_list .get-more").remove();
        }

        mandyServices.mandy_get_my_message_by_page(null, isRead, messagePageSize, currentPage).then( function (res) {
            var data = res.data;
            buildMessage(data);
        });

    }

    function loadNewData() {
        currentPage = 1;
        getPageList(1, messagePageSize);
    }
    
    function getPageList(page,pageSize) {
        //已读未读下拉列表选项值
        var isRead = $("#select_is_read option:selected").val();
        //更多消息按钮容器清空
        $("#div_message_list .get-more").remove();

        mandyServices.mandy_get_my_message_by_page(null, isRead, pageSize, page).then(function (res) {
            var data = res.data;

            //TODO 处理重复数据不要刷新页面
//            if(data!=null&&data.list!=null&&data.list.length!=0) {
//                if (searchTime != data.list[data.list.length - 1].create_time) {
//                    divMessage.empty();
//                    buildMessage(data);
//                }
//            }
            //清空整个消息列表的容器
            divMessageList.empty();
            buildMessage(data);
            currentPage++;
        });


    }

    //桌面通知
    var notice_permission = null;
    if (window.Notification){
	    Notification.requestPermission().then(function(permission) {
		    if(permission === 'granted'){
			    notice_permission = true;
			    console.log('用户允许通知');
		    }else if(permission === 'denied'){
			    console.log('用户拒绝通知');
		    }
	    });
    }

    function sendNotice(title,option) {
        return new Notification(title,option);
    }

    function buildMessage(data) {
        if (data == null || data.list == null || data.list.length == 0) {
            divMessageList.append('<div style="width: 100%; text-align: center" class="no-more">没有更多了</div>');
        } else {
            for (var i = 0; i < data.list.length; i++) {
                var table = buildMessageTable(data.list[i], taskOrPatientTable);
                var divElement = $("<div class='feed-element'>");
                divElement.append(table);
                divMessageList.append(divElement);
//                divMessage.append("<br/>");
            }          
            searchTime = data.list[data.list.length - 1].create_time;

            if (data.list.length < messagePageSize) {
                divMessageList.append('<div style="width: 100%; text-align: center" class="no-more">没有更多了</div>');
            } else {
                divMessageList.append('<div style="width: 100%; text-align: center" class="get-more"><a id="get-more" onclick="loadNextData()">更多消息&nbsp;&nbsp;<i class="fa fa-long-arrow-down"/></a></div>');
            }

        }
    }

    function openRemarkTable(id) {

        if ($("#i_fa_is_read_" + id).hasClass("fa-angle-double-down")) {
            $("#i_fa_is_read_" + id).removeClass("fa-angle-double-down");
            $("#i_fa_is_read_" + id).addClass("fa-angle-double-up");
            $("#remark_table_" + id).removeClass("hide");

//            debugger;

            if(!$("#img_read_" + id).hasClass('hide')) {
                if(unReadNum.text() - 1 >= 0) {
                    unReadNum.text(unReadNum.text() - 1);
                }
                $("#img_read_" + id).addClass("hide");
                mandy_put_message_is_read(id, function (data) {
                    $("#buss-name-" + id).css("font-weight", "normal");
                    debugAlert(data);
                });
            }

        } else {
            $("#i_fa_is_read_" + id).removeClass("fa-angle-double-up");
            $("#i_fa_is_read_" + id).addClass("fa-angle-double-down");
            $("#remark_table_" + id).addClass("hide");
        }
    }
    function remarkRead (target,id,read){

       mandyServices.mandy_put_message_is_read(id).then(function (res) {
           $(target).closest(".feed-element").find(".mark-check").addClass("hide");
       });
    }
   /* function buildMessageTable(data, tableTemp) {
        var createDate = formatDate(new Date(data.create_time));
        var createHHmm = getHHmm(new Date(data.create_time));
//        debugger;
        var sendHosName = data.send_hos.name == null ? "" : data.send_hos.name;
        var sender = data.sender.name == null ? "" : data.sender.name;
        var receiver =data.receiver == null||data.receiver.name == null ? "" : data.receiver.name;
        var receiverHosName =data.receiver_hos == null||data.receiver_hos.name == null ? "" : data.receiver_hos.name;

        var newTable = tableTemp.clone(true);

        newTable.find(".message-send-hos").text(sendHosName);
        newTable.find(".message-sender").text(sender);
        newTable.find(".create-date").text(createDate);
        newTable.find(".create-hhmm").append(createHHmm);

        var a = $("<a id='a_read_" + data.id + "'>");
        a.attr("style", "text-decoration:underline;color:#6d9dcd");
        a.attr("onclick", "openRemarkTable('" + data.id + "')");
        a.append('<i class="fa fa-angle-double-down" style="font-size:20px" id="i_fa_is_read_' + data.id + '"></i>');
        newTable.find(".is-read").append(a);

        //标题
        newTable.find(".buss-name").html(messageTitleArray[data.buss_type - 1]);
        newTable.find(".buss-name").attr("id", "buss-name-" + data.id);

        if (!data.is_read == 1) {
            newTable.find(".create-hhmm").append('<img id="img_read_' + data.id + '" src="/img/message/un_read.jpg" style="vertical-align:top;width: 8px"/>');
            newTable.find(".buss-name").css("font-weight", "bold");
        }else{
            newTable.find(".create-hhmm").append('<img id="img_read_' + data.id + '" src="/img/message/un_read.jpg" style="vertical-align:top;width: 8px" class="hide"/>');
        }

        var remarkStr = data.remark;

        if (remarkStr != null && remarkStr != '') {
            var remark = eval("(" + remarkStr + ")");
            var detailInfo = "";
            if (data.buss_type == 1) {
                detailInfo = '<b>'+sendHosName + data.sender.name +'</b>'+ '医生发布了转诊信息,患者<b>(PATIENTCONTENT)</b>。<br/>\
                                转诊说明：\
                            '+(remark.prescribed==null?"":remark.prescribed);
                detailInfo = buildReferralMessage(remark,detailInfo);
                openMessageBtn(data,remark,newTable);
            } else if (data.buss_type == 2) {
                detailInfo = '发布了患者(PATIENTCONTENT)的转诊信息。';
                detailInfo = buildReferralMessage(remark,detailInfo);
                openMessageBtn(data,remark,newTable);
            } else if (data.buss_type == 3) {
                detailInfo = '您在'+new Date(remark.out_time).format("YYYY-MM-DD HH:mm")+'发布的转诊患者(PATIENTCONTENT)已有<b>'+sendHosName+sender+'</b>医生选择接收了。';
                detailInfo = buildReferralMessage(remark,detailInfo);
                openMessageBtn(data,remark,newTable);
            } else if (data.buss_type == 4) {
//                debugger;
                detailInfo = createDate + '发布的转诊患者(PATIENTCONTENT)，没有医生接诊，信息<b>已过期</b>。';
                detailInfo = buildReferralMessage(remark,detailInfo);
                openMessageBtn(data,remark,newTable);
            } else if (data.buss_type == 5) {
                detailInfo = buildTask(remark, "您收到医生" + sender + "分配的新的");
            } else if (data.buss_type == 6) {
                detailInfo = buildPatientByRecord(remark, "您收到医生" + sender + "分配的");
            } else if (data.buss_type == 7) {
                detailInfo = buildPatientByRecord(remark, "收到医生" + sender  + "给治疗师" + receiver+ "分配的新的");
            } else if (data.buss_type == 8) {
            } else if (data.buss_type == 9) {
                detailInfo = buildTask(remark, "您收到治疗师长" + sender + "分配的新的");
            } else if (data.buss_type == 10) {
            } else if (data.buss_type == 11) {
                detailInfo = buildCancelTask(remark, "治疗师长" + sender + "取消了");
            } else if (data.buss_type == 12) {
            } else if (data.buss_type == 13) {
                detailInfo = buildCancelTask(remark, "治疗师长" + sender + "取消了");;
            } else if (data.buss_type == 14) {
                detailInfo = buildTask(remark, "您收到治疗师长" + sender + "分配的新的");
            } else if (data.buss_type == 15) {
            } else if (data.buss_type == 16) {
                detailInfo = buildPatientByPrescription(remark, "您的", "被治疗师长" + sender + "重新安排了");
            } else if (data.buss_type == 17) {
                detailInfo = buildPatientByPrescription(remark, "治疗师长" + sender + "分配了新的", "给您");
            } else if (data.buss_type == 18) {
            } else if (data.buss_type == 19) {
                if("therapist" == data.sender.job) {
                    detailInfo = buildFinishTask(remark, "收到治疗师" + sender + "提交的", "的评估结果");
                }
                else {
                    detailInfo = buildFinishTask(remark, "收到医生" + sender + "提交的", "的评估结果");
                }
            } else if (data.buss_type == 20) {
            } else if (data.buss_type == 21) {
//                debugger;
                detailInfo = '您在'+new Date(remark.in_time).format("YYYY-MM-DD HH:mm")+'选择接收<b>' + sendHosName + sender + '</b>医生的患者<b>(PATIENTCONTENT)</b>,接诊已成功';
                detailInfo = buildReferralMessage(remark,detailInfo);
                openMessageBtn(data,remark,newTable);
            }

            newTable.find(".content-detail").html(detailInfo);
        }

        newTable.find(".remark-table").attr("id", "remark_table_" + data.id);
        return newTable;
    }*/
    
    //将需要加粗的字体评上css
    function fontBold(data){
    	var fontBold = JSON.parse(data.bold);
    	var content = data.content;
    	for (var key in fontBold)
	    {
    		var value = fontBold[key]; //json的value
	       // alert(key); 
    		if(content.indexOf(value) > -1){
    			content = content.replace(value,"<b> "+ value +" </b>")
    		}
	    }
    	return content;

    }
    
    function buildMessageTable(data, tableTemp) {
        var type = data.buss_type;
        //当前用户profile_id
        var profile_id = getCookie("profile_id");

        var createDate = formatDate(new Date(data.create_time));
        var createHHmm = getHHmm(new Date(data.create_time));
        var newTable = tableTemp.clone(true);
		//alert(fontBold(data));
		
        var p0 = $("<p style='word-break:break-all;'>" + fontBold(data) + "</p>");
        var p1 = $("<p class='clearfix'><b class='pull-left'>" + createDate + "&nbsp;&nbsp;" + createHHmm + "</b></p>");

        var span = $("<span class='mark-check pull-right'><i class='pull-left' style='padding: 5px;margin: 5px 5px 0 0;background-color: red;border-radius: 10px'></i><button class='btn btn-info btn-xs' onclick=remarkRead(this," + data.id + "," + data.is_read  + ")>标记已读</button></span>");

        if (data.is_read == 0){
            p1.append(span);
        }
       /*  var p2 = $("<p><button class='btn btn-primary btn-xs' onclick=setParamToUrl({emr_id:"+ data.buss_id +",dis_edit:true});loadTitle('/emr/info-title.html');remarkRead(this," + data.id + "," + data.is_read  + ")>查看病历</button></p>");

        var p3 = $("<p><button class='btn btn-primary btn-xs' onclick=setParamToUrl({emr_id:"+ JSON.parse(data.remark).out_emr.id +",transfer_id:"+ data.buss_id +",dis_edit:true});loadTitle('/emr/info-title.html');remarkRead(this," + data.id + "," + data.is_read  + ")>查看病历</button>&nbsp;&nbsp;"
            +"<button class='btn btn-primary btn-xs'onclick=receiveReferral(this," + data.buss_id + "," +data.id + ");remarkRead(this," + data.id + "," + data.is_read  + ")>接诊</button></p>");

        var p4 = $("<p><button class='btn btn-primary btn-xs' onclick=setParamToUrl({emr_id:"+ JSON.parse(data.remark).out_emr.id +",transfer_id:"+ data.buss_id +",dis_edit:true});loadTitle('/emr/info-title.html');remarkRead(this," + data.id + "," + data.is_read  + ")>查看病历</button>&nbsp;&nbsp;"
            +"<button class='btn btn-primary btn-xs'onclick=setParamToUrl({});loadTitle('/referral/transfer_title.html');remarkRead(this," + data.id + "," + data.is_read  + ")>前往转诊</button></p>");

        var p5 = $("<p><button class='btn btn-primary btn-xs' onclick=setParamToUrl({emr_id:"+ JSON.parse(data.remark).out_emr.id +",transfer_id:"+ data.buss_id +",dis_edit:true});loadTitle('/emr/info-title.html');remarkRead(this," + data.id + "," + data.is_read  + ")>查看病历</button></p>");

        var p6 = $("<p><button class='btn btn-primary btn-xs' onclick=setParamToUrl({prcp_item_id:"+ data.buss_id +"});loadTitle('/gauge/gauge_title.html');remarkRead(this," + data.id + "," + data.is_read  + ")>查看评估</button></p>");
 */
        if (type == 19){
        	var p6 = $("<p><a class='btn btn-primary btn-xs' href='#/evaluation/gauge?prcpItemId="+data.buss_id+"' onclick=remarkRead(this," + data.id + "," + data.is_read  + ")>查看评估</a></p>");
            if (data.status == "3" || data.status == "4"){
                p6.find("button").removeClass("btn-primary").prop("disabled",true);
            }
            newTable.append(p0,p6,p1);
        }else if(type == 30){
        	var p2 = $("<p><a class='btn btn-primary btn-xs' href='#/emr/info/"+data.buss_id+"?disEdit=1&mesEmr=1' onclick=remarkRead(this," + data.id + "," + data.is_read  + ")>查看病历</a></p>");
            if (data.status == "3" || data.status == "4"){
                p2.find("button").removeClass("btn-primary").prop("disabled",true);
            }
            newTable.append(p0,p2,p1);
        }else if(type == 3){
        	var p4 = $("<p><a class='btn btn-primary btn-xs' href='#/emr/info/"+JSON.parse(data.remark).out_emr.id+"?disEdit=1&mesEmr=1&transferId="+data.buss_id+"' onclick=remarkRead(this," + data.id + "," + data.is_read  + ")>查看病历</a>&nbsp;&nbsp;"
                    +"<a class='btn btn-primary btn-xs' href='#/referral/list' onclick=remarkRead(this," + data.id + "," + data.is_read  + ")>前往转诊</a></p>");
            if (data.status == "3" || data.status == "4") {
                p4.find("button").removeClass("btn-primary").prop("disabled",true);
            }
            newTable.append(p0,p4,p1);
        }else if(type == 4){
        	var p5 = $("<p><a class='btn btn-primary btn-xs' href='#/emr/info/"+JSON.parse(data.remark).out_emr.id+"?disEdit=1&mesEmr=1&transferId="+data.buss_id+"' onclick=remarkRead(this," + data.id + "," + data.is_read  + ")>查看病历</a></p>");
            if (data.status == "3" || data.status == "4") {
                p5.find("button").removeClass("btn-primary").prop("disabled",true);
            }
            newTable.append(p0,p5,p1);
        }else if(type == 1){
        	var p3 = $("<p><a class='btn btn-primary btn-xs'  href='#/emr/info/"+JSON.parse(data.remark).out_emr.id+"?disEdit=1&mesEmr=1&transferId="+data.buss_id+"' onclick=remarkRead(this," + data.id + "," + data.is_read  + ")>查看病历</a>&nbsp;&nbsp;"
                    +"<button class='btn btn-primary btn-xs'onclick=receiveReferral(this," + data.buss_id + "," +data.id + ");remarkRead(this," + data.id + "," + data.is_read  + ")>接诊</button></p>");
            if(data.receive_status == "0"){
                if (data.status == "2" || data.status == "3" || data.status == "4"){
                    p3.find("button").removeClass("btn-primary").prop("disabled",true);
                }
            }else if(data.receive_status == "1"){
                p3.find("button:last").text("已接诊").removeClass("btn-primary").prop("disabled",true);
                if (data.status == "1"){
                    p3.find("button:first").prop("disabled",false);
                }else if(data.status == "2"){
                    if (data.performer == null || data.performer == "null" || data.performer.id == profile_id){
                        p3.find("button:first").prop("disabled",false);
                    }else if(data.performer.id != profile_id){
                        p3.find("button:first").removeClass("btn-primary").prop("disabled",true);
                    }
                }else if(data.status == "3" || data.status == "4"){
                    p3.find("button:first").removeClass("btn-primary").prop("disabled",true);
                }
            }
            newTable.append(p0,p3,p1);
        }else {
            newTable.append(p0,p1);
        }
        return newTable;
    }

    //根据record
    function buildTask(remark, beginInfo, endInfo) {
        var type = remark.type;
        var task = remark.task;

        var EMRNum = task.prescription_item.prescription.medical_record.number;
        var patientName = getPrivatePatientName(task.patient.name);
        var patientSex = task.patient.sex == 'male' ? '男' : '女';
        var patientAge = calculateAge(task.patient.birthday);

        var record = "";
        //评估
        if (type == 1) {
            var gaugeName = task.gauge.name;
            var date = getDate(task.start_time).format("YYYY-MM-DD");
            var gaugeTime = date + " " + getDate(task.start_time).format("HH:mm") + "~" + getDate(task.end_time).format("HH:mm");
            record = "康复评估(" + gaugeName + ")";
        }
        //训练
        else if (type == 2) {
            var date = getDate(task.start_time).format("YYYY-MM-DD");
            var trainingTime = date + " " + getDate(task.start_time).format("HH:mm") + "~" + getDate(task.end_time).format("HH:mm");
            record = "康复训练(" + "<b>" + trainingTime + "</b>)";
        }

        var description = beginInfo;
        description += record;
        description += "，患者(" + EMRNum + "-" + patientName + "-" + patientSex + "-" + patientAge + ")";
        if(endInfo != null && endInfo != "") {
            description += endInfo;
        }
        return description;
    }

    function buildFinishTask(remark, beginInfo, endInfo) {
        var type = remark.type;
        var task = remark.task;

        var EMRNum = task.prescription_item.prescription.medical_record.number;
        var patientName = getPrivatePatientName(task.patient.name);
        var patientSex = task.patient.sex == 'male' ? '男' : '女';
        var patientAge = calculateAge(task.patient.birthday);

        var record = "";
        //评估
        if (type == 1) {
            var gaugeName = task.gauge.name;
            var date = getDate(task.start_time).format("YYYY-MM-DD");
            var gaugeTime = date + " " + getDate(task.start_time).format("HH:mm") + "~" + getDate(task.end_time).format("HH:mm");
            record = "康复评估(<b>" + gaugeName + "</b>)";
        }
        //训练
        else if (type == 2) {
            var date = getDate(task.start_time).format("YYYY-MM-DD");
            var trainingTime = date + " " + getDate(task.start_time).format("HH:mm") + "~" + getDate(task.end_time).format("HH:mm");
            record = "康复训练(" + "<b>" + trainingTime + "</b>)";
        }

        var description = beginInfo;
        description += record;
        description += "，患者(" + EMRNum + "-" + patientName + "-" + patientSex + "-" + patientAge + ")";
        if(endInfo != null && endInfo != "") {
            description += endInfo;
        }
        return description;
    }

    function buildCancelTask(remark, beginInfo, endInfo) {

        var type = remark.type;
        var task = remark.task;

        var description = beginInfo;

        var EMRNum = task.prescription_item.prescription.medical_record.number;
        var patientName = getPrivatePatientName(task.patient.name);
        var patientSex = task.patient.sex == 'male' ? '男' : '女';
        var patientAge = calculateAge(task.patient.birthday);
        description += "患者(<b>" + EMRNum + "-" + patientName + "-" + patientSex + "-" + patientAge + "</b>)在";

        var record = "";
        //评估
        if (type == 1) {
            var gaugeName = task.gauge.name;
            var date = getDate(task.start_time).format("YYYY-MM-DD");
            var gaugeTime = date + " " + getDate(task.start_time).format("HH:mm") + "~" + getDate(task.end_time).format("HH:mm");
            record = "(<b>" + gaugeTime + "</b>)的康复评估";
        }
        //训练
        else if (type == 2) {
            var date = getDate(task.start_time).format("YYYY-MM-DD");
            var trainingTime = date + " " + getDate(task.start_time).format("HH:mm") + "~" + getDate(task.end_time).format("HH:mm");
            record = "(<b>" + trainingTime + "</b>)的康复训练";
        }

        description += record;
        if(endInfo != null && endInfo != "") {
            description += endInfo;
        }
        return description;
    }

    //根据record
    function buildPatientByRecord(remark, beginInfo, endInfo) {
        //debugger;
        remark = remark.task;
        var EMRNum = remark.prescription_item.prescription.medical_record.number;
        var patientName = getPrivatePatientName(remark.patient.name);
        var patientSex = remark.patient.sex == 'male' ? '男' : '女';
        var patientAge = calculateAge(remark.patient.birthday);

        var description = beginInfo;
        description += "患者(<b>" + EMRNum + "-" + patientName + "-" + patientSex + "-" + patientAge + "</b>)";
        if(endInfo != null && endInfo != "") {
            description += endInfo;
        }
        return description;
    }

    //根据prescription
    function buildPatientByPrescription(remark, beginInfo, endInfo) {
        var EMRNum = remark.prescription.medical_record.number;
        var patientName = getPrivatePatientName(remark.prescription.medical_record.patient.name);
        var patientSex = remark.prescription.medical_record.patient.sex == 'male' ? '男' : '女';
        var patientAge = calculateAge(remark.prescription.medical_record.patient.birthday);

        var description = beginInfo;
        description += "患者(<b>" + EMRNum + "-" + patientName + "-" + patientSex + "-" + patientAge + "</b>)";
        if(endInfo != null && endInfo != "") {
            description += endInfo;
        }
        return description;
    }

    function buildReferralMessage(remark,content){
        var EMRNum = remark.out_emr.number;
        var patientName = getPrivatePatientName(remark.out_emr.patient.name);
        var patientSex = remark.out_emr.patient.sex == 'male' ? '男' : '女';
        var patientAge = calculateAge(remark.out_emr.patient.birthday);

        var patientContent = EMRNum + '-' + patientName
                + '-' + patientSex + '-' + patientAge;

        content = content.replace("PATIENTCONTENT",patientContent);

        return content;
    }

    function receiveReferral(target,bussId, messageId) {
        receiveEMRConfirm(target,bussId, messageId);
    }

    function openMessageBtn(data,remark,messageTable){
        messageTable.find(".look-or-receive").removeClass("hide");

        if(data.buss_type== 1 || data.buss_type == 3 || data.buss_type == 4 || data.buss_type == 21){
            if(data.status != 2 || (data.receive!=null && data.receive.id == getCookie("profile_id")) || (data.performer !=null &&data.performer.id == getCookie("profile_id")) || data.buss_type == 4 ||data.buss_type == 21){
                var param = {};
                param.emr_id = remark.out_emr.id;
                param.transfer_id = data.buss_id;

                messageTable.find(".a-show-emr").removeClass("hide");
                messageTable.find(".a-show-emr").attr("onclick", "setParamToUrl(" + JSON.stringify(param) + ");loadTitle('/emr/info-title.html');");
            }
        }

        if(data.buss_type == 1 || data.buss_type == 21){
            messageTable.find(".btn-receive").attr("id","btn_receive_" + data.id);
            messageTable.find(".btn-receive").removeClass("hide");
            messageTable.find(".btn-receive").attr("onclick", "receiveReferral('" + data.buss_id + "','" + data.id + "')");

            //已接诊
            if(data.receive_status > 0) {
                messageTable.find(".btn-receive").text("已接收");
                messageTable.find(".btn-receive").attr('disabled',true);
                messageTable.find(".btn-receive").addClass("btn-default");
            }
            //被处理
            else if(data.status==2){
                messageTable.find(".btn-receive").text("已被接收");
                messageTable.find(".btn-receive").attr('disabled',true);
                messageTable.find(".btn-receive").addClass("btn-default");
            }
        }


    }

    function receiveEMRConfirm(target,bussId, messageId) {

        var target = $(target);
        var r=confirm("确认接收此患者?")
        if (r==true)
        {
            mandyServices.mandy_put_referral_emr(bussId, messageId).then(function (res) {
                var data = res.data;
                log("+++++++接诊++++++++")
                log(data)
                log("+++++++接诊++++++++")
                toastr.success("接收成功");
                //var btnReceive = $("#btn_receive_" + messageId);
                target.text('已接收');
                //target.addClass("btn-default");
                target.attr('disabled',true);
            });
            
            
        }
        else
        {
           console.log("取消接收");
        }
    }
    layui.use([ 'mandyServices','utils'], function ( _mandyServices,utils) {
        mandyServices = _mandyServices;
        getPageList(1, messagePageSize);

        //接收系统推送的消息,更新消息列表或我的任务
        utils.ARES.webSocket && (utils.ARES.webSocket.onmessage = function(event){
            console.log('@@@@@@@@@@@@@@@@websocket Message@@@@@@@@@@@@@@@@')
            console.log(event.data)
            if(event.data == '2') {
                sendNotice("消息提醒",{
                    body: '你有新的消息，请及时查看!',
                    tag: 'notice',
                    icon: './images/notice.gif',
                })
                intervalLoadNewData();
                $("#not-read-alarm").removeClass("hide");
            }else if (event.data == '1'){
                sendNotice("消息提醒",{
                    body: '你有新的任务，请及时完成!',
                    tag: 'notice',
                    icon: './images/notice.gif',
                })
            }
        })
    })

</script>

</html>
